package com.imooc.demo.service.impl;

import com.imooc.demo.dataobject.ProductInfo;
import com.imooc.demo.dto.CartDTO;
import com.imooc.demo.enums.ProductStatusEnum;
import com.imooc.demo.enums.ResultEnum;
import com.imooc.demo.exception.SellException;
import com.imooc.demo.repository.ProductCategoryRepository;
import com.imooc.demo.repository.ProductInfoRepository;
import com.imooc.demo.service.ProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: 杨通通
 * @Date: 2021/11/3 22:18
 * @Description:
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findById(String id) {


        return repository.findById(id).get();
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductStatusEnum.UP.getStatus());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {

//        ProductInfo info = new ProductInfo();
//        repository.findAll(Example.of(info),pageable);
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
//        repository.save()
        return repository.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> list) {
        for(CartDTO cartDTO:list){
            ProductInfo productInfo = repository.findById(cartDTO.getProductId()).get();
            Integer newStock = productInfo.getProductStock()+ cartDTO.getProductQuantity();
            productInfo.setProductStock(newStock);
            repository.save(productInfo);
        }
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> list) {
            for(CartDTO cartDTO:list){
                ProductInfo productInfo = repository.findById(cartDTO.getProductId()).get();
                if(productInfo == null){
                    throw new SellException(ResultEnum.PRODUCT_NOT_EXISTS);
                }
                Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
                if(result< 0){
                    throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
                }
                productInfo.setProductStock(result);
                repository.save(productInfo);

            }
    }
}